import Vue from "vue";
import Crypto from "./crypto";

const vm = new Vue();

const Util = {
  hasKey(obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
  },
  getUrlParam(name) {
    var reg = new RegExp("(^|/?|&)" + name + "=([^&]*)(&|#)", "i");
    var l = window.location.href;
    var i = l.indexOf("?");
    if (i < 0) return null;
    var str = l.slice(i + 1, l.length);
    if (str) {
      var r = str.match(reg);
      if (r) {
        return unescape(r[2]);
      }
    }
    return null;
  },
  postLoading(callback, data, text) {
    if (text) {
      this.openLoading(text);
    } else {
      this.openLoading();
    }
    return new Promise(resolve => {
      callback(data)
        .then(res => {
          this.closeLoading();
          resolve(res);
        })
        .catch(() => {
          this.closeLoading();
        });
    });
  },
  /**
   * 设置cookie
   * @param key  key
   * @param value 值
   * @param time  保存时间（天）
   */
  setCookie(key, value, time) {
    var cur = new Date();
    cur.setTime(cur.getTime() + time * 24 * 3600 * 1000);
    document.cookie =
      key +
      "=" +
      encodeURIComponent(value) +
      ";expires=" +
      (time ? cur.toGMTString() : "");
  },
  getCookie(key) {
    var data = document.cookie;
    var startIndex = data.indexOf(key + "=");
    if (startIndex > -1) {
      startIndex = startIndex + key.length + 1;
      var endIndex = data.indexOf(";", startIndex);
      endIndex = endIndex < 0 ? data.length : endIndex;
      return decodeURIComponent(data.substring(startIndex, endIndex));
    } else {
      return "";
    }
  },
  delCookie(key) {
    var data = this.getCookie(key);
    if (data !== false) this.setCookie(key, data, -1);
  },
  /**
   *
   * @param key key
   * @param value value
   * @param encode 是否加密存储
   */
  setSessionStorage(key, value, encode) {
    let str = window.JSON.stringify(value);
    if (encode) {
      str = Crypto.encrypt(str);
    }
    window.sessionStorage.setItem(key, str);
  },
  getSessionStorage(key, decode) {
    var str = "";
    str = window.sessionStorage.getItem(key);
    if (!str) return "";
    if (decode) {
      str = Crypto.decrypt(str);
    }
    try {
      return window.JSON.parse(str);
    } catch (error) {
      window.sessionStorage.removeItem(key);
      window.location.reload();
    }
  },
  setLocalStorage(key, value, encode) {
    let str = window.JSON.stringify(value);
    if (encode) {
      str = Crypto.encrypt(str);
    }
    window.localStorage.setItem(key, str);
  },
  getLocalStorage(key, decode) {
    var str = "";
    str = window.localStorage.getItem(key);
    if (!str) return "";
    try {
      if (decode) str = Crypto.decrypt(str);
      return window.JSON.parse(str);
    } catch (error) {
      window.localStorage.removeItem(key);
      window.location.reload();
    }
  },
  /**
   * 全屏覆盖加载动画
   * @param  {String} text  加载提示文字 (默认 "加载中...")"
   */
  openLoading(text = "加载中...") {
    window.fullLoading = vm.$loading({
      lock: true,
      text: text,
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.66)"
    });
  },
  closeLoading() {
    if (window.fullLoading) window.fullLoading.close();
  },
  isNumber(val) {
    let pattern = /^[1-9]{1}\d*$/g;
    let isNumber = pattern.test(val);
    return isNumber;
  },
  isLink(val) {
    let pattern = /^((https:|http:|:)?\/\/)(?:[\da-z.-]+)\.(?:[a-z.]{2,6})(?:\/\w\.-]*)*\/?/;
    let isLink = pattern.test(val);
    return isLink;
  },
  checkLink(val) {
    let isLink = this.isLink(val);
    if (!isLink) vm.$message.error("请输入正确的网址");
  },
  /**
   * 四舍五入强制保留n位小数
   * @param  x  操作数字
   * @param  n 保留位数
   */
  toDecimal(x, n) {
    var f = parseFloat(x);
    if (isNaN(f) && isNaN(n)) {
      return false;
    }
    if (n === 0) return Math.round(x);
    var num = Number("1E" + n);
    f = Math.round(x * num) / num;
    var s = f.toString();
    var rs = s.indexOf(".");
    if (rs < 0) {
      rs = s.length;
      s += ".";
    }
    while (s.length <= rs + n) {
      s += "0";
    }
    return s;
  },
  /**
     * 缓冲函数
     * @param {Object} dom 目标dom
     * @param {Number} destination 目标位置
     * @param {Number} rate 缓动率
     * 示例用法
     var dom = document.documentElement || document.body;
     this.$util.easeout(dom, 0, 5);
     */
  easeout(dom, destination = 0, rate = 3) {
    let position = dom.scrollTop;
    if (
      position === destination ||
      typeof destination !== "number" ||
      rate === 0
    ) {
      return false;
    }
    // 不存在原生`requestAnimationFrame`，用`setTimeout`模拟替代
    if (!window.requestAnimationFrame) {
      window.requestAnimationFrame = function(fn) {
        return setTimeout(fn, 17);
      };
    }
    let step = function() {
      position = position + (destination - position) / rate;
      if (Math.abs(destination - position) < 1) {
        //动画结束
        dom.scrollTop = destination;
        return;
      }
      dom.scrollTop = position;
      requestAnimationFrame(step);
    };
    step();
  },
  /**
   * 对象深拷贝
   * @param {Object} obj 初始对象
   * @return {Object} result 拷贝后对象
   */
  deepClone(obj) {
    let result = Array.isArray(obj) ? [] : {};
    for (let key in obj) {
      if (this.hasKey(obj, key)) {
        if (typeof obj[key] === "object") {
          result[key] = this.deepClone(obj[key]); //递归复制
        } else {
          result[key] = obj[key];
        }
      }
    }
    return result;
  },

  showLoading(text = "加载中...") {
    /*window.fullLoading = vm.$loading({ text: text })*/
    window.fullLoading = vm.$loading({
      lock: true,
      text: text,
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.66)"
    });
  },
  hideLoading() {
    if (window.fullLoading) window.fullLoading.close();
  },
  other(m) {
    return m < 10 ? "0" + m : m;
  },
  // 时间蹉转换成日期
  time(time) {
    //接收一个时间戳， time是整数，否则要parseInt转换
    let timer = new Date(time);
    let y = timer.getFullYear();
    let m = timer.getMonth() + 1;
    let d = timer.getDate();
    // let h = timer.getHours();
    // let mm = timer.getMinutes();
    // let s = timer.getSeconds();
    // return y+'-'+m+'-'+d+' '+h+':'+mm+':'+s;
    return y + "-" + this.other(m) + "-" + this.other(d);
  }
};

export default Util;
